<template>
  <div>
    <el-form size="small" label-width="100px" label-position="left" v-if="form">
      <el-form-item v-for="(item,key) in form.form" :key="key" :label="item.name">
        <div v-if="item.name != '国籍' && item.name != '城市'" class="input-box-div">
          <el-input
            type="text"
            :placeholder="'请输入'+item.name"
            v-if="item.type == 'text'"
            v-model="item.value"
            :disabled="item.name == '姓名' || item.name == '手机号'  ? true : false"
          ></el-input>
          <el-input
            type="number"
            :placeholder="'请输入'+item.name"
            v-if="item.type == 'number'"
            v-model="item.value"
            :disabled="item.name == '姓名' || item.name == '手机号'  ? true : false"
          ></el-input>
          <el-input
            type="textarea"
            :placeholder="'请输入'+item.name"
            v-if="item.type == 'textarea'"
            v-model="item.value"
          ></el-input>
          <el-select
            v-if="item.type == 'select'"
            v-model="item.value"
            class="unit-form-view-select"
          >
            <el-option
              v-for="(items,keys) in item.data"
              :key="keys"
              :label="items.label"
              :value="items.label"
            ></el-option>
          </el-select>
          <el-date-picker
            v-if="item.type == 'date'"
            class="unit-form-view-select"
            type="date"
            placeholder="选择日期时间"
            v-model="item.value"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
          <el-radio-group v-model="item.value" v-if="item.type == 'radio' && item.name != '性别'">
            <el-radio
              v-for="(items,keys) in item.data"
              :key="keys"
              :label="items.value"
            >{{items.label}}</el-radio>
          </el-radio-group>
          <el-radio-group v-model="item.value" v-if="item.type == 'radio' && item.name == '性别' ">
            <el-radio label="男" :disabled="item.limit == 2 ? true : false">男</el-radio>
            <el-radio label="女" :disabled="item.limit == 1 ? true : false">女</el-radio>
          </el-radio-group>
          <div class="unit-form-view-image-view" v-if="item.type == 'image' ">
            <img :src="item.value" style="width:100%;">
            <input type="file" class="unit-form-view-image-view-file" @change="changeFile($event,key)">
          </div>
        </div>
        <div v-if="item.name == '国籍'" class="input-box-div">
          <el-select v-model="item.value" class="unit-form-view-select">
            <el-option v-for="(items,keys) in nation" :key="keys" :label="items" :value="items"></el-option>
          </el-select>
        </div>
        <div v-if="item.name == '城市'" class="input-box-div">
          <el-cascader  class="unit-form-view-select"
            v-model="area_select"
            :options="area_arr"
            :props="{ expandTrigger: 'hover' }"
            @change="handleChange"
          ></el-cascader>
        </div>
        <div class="input-memo-div" v-if="item.not_null">*必填</div>
      </el-form-item>
      <el-form-item>
        <el-button class="com-btn" @click="submit()">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import proJs from "../../../assets/js/province.js";
import cityJs from "../../../assets/js/city.js";
import nationJs from "../../../assets/js/nation.js";

export default {
  props: { form_data: {} },
  data() {
    return {
      form: {},
      nation: [],
      area_arr: [],
      area_select : []
    };
  },
  mounted() {
    this.form = JSON.parse(JSON.stringify(this.form_data));
    this.nation = nationJs;
    for (var i in proJs) {
      var area_temp = proJs[i];
      area_temp.children = cityJs[i];
      this.area_arr.push(area_temp);
    }
    //初始化城市
    this.initCity();
  },
  methods: {
    //上传图片
    changeFile(e,keyss){
      var file = e.currentTarget.files;
      var img = file[0];
      if (img == undefined) return false;
      //获取文件后缀名
      var arr = img["name"].split(".");
      var img_type = arr[1];
      let OSS = require("ali-oss");
      let client = new OSS({
        region: "oss-cn-hangzhou",
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，部署在服务端使用RAM子账号或STS，部署在客户端使用STS。
        accessKeyId: "LTAIWdxCuPiIzLfm",
        accessKeySecret: "z1zLih5CgWNkWfuzHj7SbpJKVdME2a",
        bucket: "ykp-new"
      });
      // client.options.endpoint.protocol = "https:";
      //获取当前时间
      var date = new Date();
      var file_name =
        date.getFullYear() +
        "/" +
        (date.getMonth() + 1) +
        "/" +
        date.getDate() +
        "/" +
        date.getHours() +
        "_" +
        date.getMinutes() +
        "_" +
        date.getSeconds() +
        "_" +
        date.getMilliseconds();
      let filename = "/active/cover/" + file_name + "." + img_type;
      let res_file = img;
      let that = this;
      async function put() {
        try {
          //object-name可以自定义为文件名（例如file.txt）或目录（例如abc/test/file.txt）的形式，实现将文件上传至当前Bucket或Bucket下的指定目录。
          let result = await client
            .multipartUpload(filename, res_file, {
              progress: percentage => {
                //console.log(percentage); // 上传文件进度
              }
            })
            .then(res => {
              that.form.form[keyss].value = that.$oss_url + res.name;
              console.log(res);
            })
            .catch(err => {
              return that.toast(0, "上传失败");
            });
        } catch (e) {
          return that.toast(0, "上传失败");
        }
      }
      put();
    },
      //初始化城市
      initCity(){
          var str = '';
          for(var y in this.form.form) {
              if(this.form.form[y].name == '城市') str = this.form.form[y].value;
          }
          var province = '';
          var city = '';
          var arr = str.split('/');
          for(var i in proJs) {
              if(proJs[i].label == arr[0])province = proJs[i].value;
              for(var x in cityJs[i]) {
                if(cityJs[i][x].label == arr[1])city = cityJs[i][x].value;
              }
          }
          this.area_select = [province,city];
      },
      //选择城市
      handleChange(){
          var arr = this.area_select;
          var province = '';
          var city = '';
          for(var i in proJs) {
              if(proJs[i].value == arr[0])province = proJs[i].label;
              for(var x in cityJs[i]) {
                if(cityJs[i][x].value == arr[1])city = cityJs[i][x].label;
              }
          }
          for(var y in this.form.form) {
              if(this.form.form[y].name == '城市')this.form.form[y].value = province+'/'+city;
          }
      },
    //保存信息
    submit() {
      this.handleChange();
      for (var i in this.form.form) {
        if (this.form.form[i].not_null && !this.form.form[i].value)
          return this.toast(0, this.form.form[i].name + "不能为空");
        if(this.form.form[i].name == '手机号') {
            var pattern = /^1[345678]\d{9}$/;
            if(!pattern.test(this.form.form[i].value)){
                return this.toast(0, this.form.form[i].name + "格式错误");
            }
        }
        if(this.form.form[i].name == '紧急联系方式') {
            var pattern = /^1[345678]\d{9}$/;
            if(!pattern.test(this.form.form[i].value)){
                return this.toast(0, this.form.form[i].name + "必须为手机号");
            }
        }
        // if(this.form.form[i].name == '证件类型' && this.form.form[i].value == '身份证') {
        //     return console.log(this.form.form[i]);
        // }
        if(this.form.form[i].name == '邮箱') {
            var pattern = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"); //正则表达式
            if(!pattern.test(this.form.form[i].value)){
                return this.toast(0, this.form.form[i].name + "格式错误");
            }
        }
      }
      this.ajaxs("active/editActiveUser", {
        data: this.form,
        success: res => {
          this.toast(res.code, res.msg);
          if (res.code) {
            this.$emit("save");
          }
        }
      });
    }
  },
  watch: {
    form_data: {
      handler() {
        this.form = JSON.parse(JSON.stringify(this.form_data));
      },
      deep: true
    }
  }
};
</script>

<style>
.input-box-div{
  width: calc(100% - 50px);
  float: left;
}
.input-memo-div{
  float: left;
  margin-left: 20px;
  color: #F56C6C;
  font-size: 12px;
}
.unit-form-view-image-view{
  max-width: 100%;
  position: relative;
}
.unit-form-view-image-view-file{
  position: absolute;
  width: 100%;
  height: 100%;
  top:0;
  left:0;
  opacity: 0;
  z-index: 1;
  cursor: pointer;
}
</style>